-module(gen_server_cter).
-behaviour(supervisor).
-include("logagent.hrl").

-export([start_link/3]).
-export([cast/2, call/2]).

%% for supervisor
-export([init/1]).

-export([behaviour_info/1]).

-spec behaviour_info(atom()) -> 'undefined' | [{atom(), byte()}].
behaviour_info(callbacks) ->                        
    [{get_name,1}];
behaviour_info(_Other) ->
    undefined.


%% @doc start the server
start_link(CterName, CbMod, Args) ->
    Ret = {ok, _Pid} = supervisor:start_link({local, CterName}, ?MODULE, [{callback, CbMod}, {args, Args}]),
    io:format("pid:~p~n", [_Pid]),
    N = erlang:system_info(schedulers),
    [{ok, _} =  supervisor:start_child(CterName, [{index, I}]) || I <- lists:seq(1, N)],
    Ret. 

%% @doc 
cast(CbMod, Req) ->
    Handler = select_handler(CbMod),
    io:format("handler is:~p~n", [Handler]),
    gen_server:cast(Handler, Req).

call(CbMod, Req) ->
    Handler = select_handler(CbMod),
    gen_server:call(Handler, Req).


%%
%% supervisor callbacks
%%
init([{callback, CbMod}, {args, Args} | _]) -> 
    Strategy = {simple_one_for_one, 10, 10},
    Mod = {undefined, {CbMod, start_link, Args},
		  permanent, 3000, worker, [CbMod]},
    {ok, {Strategy, [Mod]}}.

%% internal API
select_handler(CbMod) ->
    I = erlang:system_info(scheduler_id),
    CbMod:get_name(I).
